
'use strict'
var getRawBody = require("raw-body")
var tenpay = require('tenpay');
var xml2js = require('xml2js')
var moment = require('moment')
module.exports = function* (ctx) {

	var xml = yield getRawBody(ctx.req, {
		length: ctx.request.length,
		limit: '1mb',
		encoding: 'utf8'
	});

	var parseXML = function (xml, callback) {
		xml2js.parseString(xml, {
			trim: true,
			explicitArray: false
		}, function (err, result) {
			err ? callback(err) : callback(null, result ? result.xml : {});
		});



	}
	var xml_result = {}
	parseXML(xml, function (err, result) {
		xml_result = result
	})
	xml_result.time_end = moment().format("YYYY-MM-DD HH:mm:ss")
	const result = yield ctx.service.wechat.find_out_trade_no_user([xml_result.openid, xml_result.out_trade_no])
	if (result && (xml_result.result_code == "SUCCESS" && xml_result.return_code == "SUCCESS")) {
		// const row={
		// 	out_trade_no:xml_result.out_trade_no,
		// 	out_trade_no_end_time:xml_result.time_end,
		// 	out_trade_no_status:"2"
		// }

		const _arr = [xml_result.out_trade_no]
		const result_find_out_trade_no_user = yield ctx.service.wechat.find_out_trade_no(_arr)

		if (result_find_out_trade_no_user[0].out_trade_no_status == "0") {
			const arr1 = ["1", xml_result.time_end, xml_result.out_trade_no]
			const arr2 = [xml_result.total_fee, xml_result.total_fee, xml_result.openid]
			const a = yield ctx.service.wechat.update_out_trade_no_user(arr1)
			const b = yield ctx.service.wechat.update_Recharge_user(arr2)
			console.log('订单余额更新成功成功')



			yield ctx.service.ws.send_websocket("订单已支付")
			console.log("订单已支付发送成功")

		}
		

		ctx.body = `<xml> 
  <return_code><![CDATA[SUCCESS]]></return_code>
  <return_msg><![CDATA[OK]]></return_msg>
</xml> 
`
	} else {
		console.log("失败")
	}


}
